﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;

namespace HostFileChangerEnhanced
{
    public partial class Form1 : Form
    {
        #region Class Initializers

        public Form1()
        {
            InitializeComponent();
            DoBasicLoad();
        }

        private void DoBasicLoad()
        {
            try
            {
                BuildDomainsForMenu();
                ViewConfiguration();
            }
            catch (Exception ex)
            {
                DialogResult userActionResult = MessageBox.Show("Possible access to host file is not permitted.\nTry to run in Administrator mode.\n\nOr Windows is not installed to the default volume (C:) or directory.\n\nError Details:\n" + ex.ToString(), "Application Run Time Error, Cannot run", MessageBoxButtons.RetryCancel, MessageBoxIcon.Error);
                if (userActionResult == System.Windows.Forms.DialogResult.Cancel)
                {
                    this.Close();
                    //Application.ExitThread();
                    Application.Exit();
                }
                else
                    DoBasicLoad();
            }
        }

        #endregion

        #region Helpers for Configuration Presentation

        private void ViewConfiguration()
        {
            lbDomainsManaged.Items.Clear();
            foreach (HostFileManagedDomains.domainsToManageRow drow in ManageManagedDomainsConfiguration.ManagedDomainsData.Rows)
            {
                foreach (HostFileManagedDomains.domainOptionsRow drowO in ManageManagedDomainsConfiguration.GetDomainOptions(drow))
                {
                    lbDomainsManaged.Items.Add(drowO.c_DomainName + " - " + drowO.c_AlternateName + " - " + drowO.c_AlternateIp);
                }
            }
        }

        #endregion

        #region Helpers for Context Menu

        private void BuildDomainsForMenu()
        {
            //first clean the ones which does not belong to here anymore
            List<ToolStripMenuItem> domainMenuItemsToRemove = new List<ToolStripMenuItem>(changerMenu.Items.Count - 2);
            while (changerMenu.Items.Count > 3)
            {
                changerMenu.Items.RemoveAt(0);
            }

            foreach (HostFileManagedDomains.domainsToManageRow drow in ManageManagedDomainsConfiguration.ManagedDomainsData.Rows)
            {
                ToolStripMenuItem aDomainForToolStrip = new ToolStripMenuItem();
                aDomainForToolStrip.Text = drow.c_DomainName;
                aDomainForToolStrip.MouseEnter += new EventHandler(domainToolStripMenuItem_MouseEnter);
                //aDomainForToolStrip.DoubleClick += new EventHandler(domainToolStripMenuItem_DoubleClick);
                aDomainForToolStrip.Click += new EventHandler(domainToolStripMenuItem_Click);
                //aDomainForToolStrip.
                if (!HostsFileHandler.IsSiteInHostsFile(drow.c_DomainName))
                    aDomainForToolStrip.Image = HostFileChangerEnhanced.Properties.Resources.i_world;
                else
                    aDomainForToolStrip.Image = HostFileChangerEnhanced.Properties.Resources.i_disconnect;

                ToolStripMenuItem aDomainLiveOptionForToolStrip = new ToolStripMenuItem();
                aDomainLiveOptionForToolStrip.Text = "Live";
                aDomainLiveOptionForToolStrip.Tag = drow.c_DomainName;
                //aDomainLiveOptionForToolStrip.Enabled = HostsFileHandler.IsSiteInHostsFile(drow.c_DomainName);
                aDomainLiveOptionForToolStrip.Click += new EventHandler(liveToolStripMenuItem_Click);

                aDomainForToolStrip.DropDownItems.Add(aDomainLiveOptionForToolStrip);

                foreach (HostFileManagedDomains.domainOptionsRow drowO in ManageManagedDomainsConfiguration.GetDomainOptions(drow))
                {
                    ToolStripMenuItem aDomainDevOptionForToolStrip = new ToolStripMenuItem();
                    aDomainDevOptionForToolStrip.Text = drowO.c_AlternateName;
                    aDomainDevOptionForToolStrip.Tag = drow.c_DomainName + "|" + drowO.c_AlternateIp;
                    aDomainDevOptionForToolStrip.Click += new EventHandler(developmentToolStripMenuItem_Click);
                    //aDomainDevOptionForToolStrip.Enabled = !HostsFileHandler.IsDomainIpInHostsFile(drow.c_DomainName, drowO.c_AlternateIp);
                    aDomainForToolStrip.DropDownItems.Add(aDomainDevOptionForToolStrip);
                }

                changerMenu.Items.Insert(0, aDomainForToolStrip);
            }
        }

        private string[] GetDomainSubItemDetailParts(ToolStripMenuItem activeSubItem)
        {
            string[] optionDetailParts = null;

            if (activeSubItem == null)
                return null;

            string optionDetails = activeSubItem.Tag as string;
            if (optionDetails == null)
                return null;

            optionDetailParts = optionDetails.Split('|');
            if (optionDetailParts.Length != 2)
                return null;

            return optionDetailParts;
        }

        private void CleanAllCheckStatusToFalse()
        {
            foreach (ToolStripItem activeMenuItem in changerMenu.Items)
            {
                if (activeMenuItem is ToolStripMenuItem)
                {
                    ((ToolStripMenuItem)activeMenuItem).Checked = false;
                }

            }
            
        }

        #endregion

        #region Event Handlers for Context Menu

        private void domainToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ToolStripMenuItem aDomainDevOptionForToolStrip = sender as ToolStripMenuItem;
            if (!aDomainDevOptionForToolStrip.Checked)
            {
                CleanAllCheckStatusToFalse();
                aDomainDevOptionForToolStrip.Checked = true;
            }
            else
                System.Diagnostics.Process.Start("http://" + aDomainDevOptionForToolStrip.Text);
        }

        private void developmentToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ToolStripMenuItem aDomainDevOptionForToolStrip = sender as ToolStripMenuItem;

            string[] optionDetailParts = GetDomainSubItemDetailParts(aDomainDevOptionForToolStrip);
            if (optionDetailParts == null)
                return;

            HostsFileHandler.ChangeTheIpOfDomainName(optionDetailParts[0], optionDetailParts[1]);
            BuildDomainsForMenu();
        }

        private void liveToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ToolStripMenuItem aDomainLiveOptionForToolStrip = sender as ToolStripMenuItem;
            if (aDomainLiveOptionForToolStrip == null)
                return;

            HostsFileHandler.RemoveDomainNameFromHostFile(aDomainLiveOptionForToolStrip.Tag as string);
            BuildDomainsForMenu();
        }

        private void domainToolStripMenuItem_MouseEnter(object sender, EventArgs e)
        {
            ToolStripMenuItem activeDomain = sender as ToolStripMenuItem;
            string domainName = activeDomain.Text;
            foreach (ToolStripMenuItem domainSubItem in activeDomain.DropDownItems)
            {
                if (domainSubItem.Text == "Live")
                {
                    domainSubItem.Enabled = HostsFileHandler.IsSiteInHostsFile(domainName);
                }
                else
                {
                    string[] optionDetailParts = GetDomainSubItemDetailParts(domainSubItem);
                    if (optionDetailParts == null)
                        continue;

                    domainSubItem.Enabled = !HostsFileHandler.IsDomainIpInHostsFile(domainName, optionDetailParts[1]);
                }
            }
        }

        private void exitToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }

        private void configureToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.Show();
            this.WindowState = FormWindowState.Normal;
            this.BringToFront();
        }


        private void changerMenu_Opened(object sender, EventArgs e)
        {
            CleanAllCheckStatusToFalse();
        }
        #endregion

        #region Event handlers for Configuration Screen

        private void bNewCancel_Click(object sender, EventArgs e)
        {
            this.tbDomainName.Text = "";
            this.tbAlternateName.Text = "";
            this.tbAlternateIp.Text = "";
        }


        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (e.CloseReason == CloseReason.UserClosing)
            {
                this.Hide();
                e.Cancel = true;
            }
        }

        private void bSave_Click(object sender, EventArgs e)
        {
            ManageManagedDomainsConfiguration.AddNewDomainSetting(tbDomainName.Text, tbAlternateName.Text, tbAlternateIp.Text);
            BuildDomainsForMenu();
            ViewConfiguration();
        }

        private void lbDomainsManaged_DoubleClick(object sender, EventArgs e)
        {
            string[] domainParts = (lbDomainsManaged.SelectedItem as string).Replace(" ", "").Split('-');
            tbDomainName.Text = domainParts[0];
            tbAlternateName.Text = domainParts[1];
            tbAlternateIp.Text = domainParts[2];
        }

        private void bRemove_Click(object sender, EventArgs e)
        {
            ManageManagedDomainsConfiguration.RemoveDomainSetting(lbDomainsManaged.SelectedItem as string);
            BuildDomainsForMenu();
            ViewConfiguration();
        }
        #endregion



    }
}
